﻿using System.Collections.Generic;
using Kratos.Framework.ContentManagement.Models.SystemRights;
using Kratos.Framework.Modules.Core.Repositories;
using Kratos.Framework.Repositories;

namespace Kratos.Framework.Modules.Core.Services.Impl
{
    public class MenuPermissionService : IMenuPermissionService
    {
        private readonly IRepository<MenuPermission> _menuRep;

        public MenuPermissionService(IRepository<MenuPermission> menuRep)
        {
            _menuRep = menuRep;
        }

        public IEnumerable<MenuPermission> GetMenu(int parentId)
        {
            var models = GetMenuById(parentId).Children;

            return models;
        }

        public MenuPermission GetMenuById(int id)
        {
            return _menuRep.GetById(id);
        }

        public void Update(MenuPermission menu)
        {
            var model = GetMenuById(menu.Id.Value);

            model.MenuName = menu.MenuName;
            model.ActionName = menu.ActionName;
            model.ControllerName = menu.ControllerName;
            model.ActionDescription = menu.ActionDescription;
            model.ControllerDescription = menu.ControllerDescription;
            model.NodeLevel = menu.NodeLevel;
            model.PrevIcon = menu.PrevIcon;
            model.Url = menu.Url;

            _menuRep.SaveOrUpdate(model);
        }

        public void Save(MenuPermission menu)
        {
            if (menu.ParentId != null && menu.ParentId.Value <= 0) menu.ParentId = null;
            _menuRep.Save(menu);
        }

        public void Delete(MenuPermission menu)
        {
            _menuRep.DeleteOnSubmit(menu);
        }

        public IEnumerable<MenuPermission> GetMenusByLevel(int level)
        {
            return _menuRep.GetAll().GetMenusByLevel(level);
        }
    }
}
